package alibaba

import (
	"boticz/app/global/variable"
	"fmt"
	"math/rand"
	"time"

	"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
)

// SendSMS 发送阿里云短信
func SendSMS(phoneNumbers, signName, templateCode, templateParam string) error {
	// 创建配置
	config := sdk.NewConfig()

	accessKeyId := variable.ConfigYml.GetString("AliSMS.accessKeyId")
	accessKeySecret := variable.ConfigYml.GetString("AliSMS.accessKeySecret")

	// 创建凭证
	cred := credentials.NewAccessKeyCredential(accessKeyId, accessKeySecret)

	// 创建客户端
	client, err := dysmsapi.NewClientWithOptions(
		"cn-hangzhou", // 地域ID
		config,
		cred,
	)
	if err != nil {
		return fmt.Errorf("创建客户端失败: %v", err)
	}

	// 创建请求
	request := dysmsapi.CreateSendSmsRequest()
	request.PhoneNumbers = phoneNumbers   // 接收短信的手机号码，多个号码用逗号分隔
	request.SignName = signName           // 短信签名
	request.TemplateCode = templateCode   // 短信模板ID
	request.TemplateParam = templateParam // 模板参数，JSON格式

	// 发送请求
	response, err := client.SendSms(request)
	if err != nil {
		return fmt.Errorf("发送短信失败: %v", err)
	}

	// 检查响应
	if response.Code != "OK" {
		return fmt.Errorf("短信发送失败，错误码: %s，错误信息: %s", response.Code, response.Message)
	}

	fmt.Printf("短信发送成功，请求ID: %s，BizID: %s\n", response.RequestId, response.BizId)
	return nil
}

// GenerateSMSCodeWithoutLeadingZero 生成不带前导零的数字验证码
func GenerateSMSCodeWithoutLeadingZero(length int) string {
	// 设置随机种子
	rand.Seed(time.Now().UnixNano())

	// 定义数字字符集
	digits := "0123456789"

	// 第一位不能是 0
	code := string(digits[1+rand.Intn(len(digits)-1)])

	// 生成剩余位数
	for i := 1; i < length; i++ {
		code += string(digits[rand.Intn(len(digits))])
	}

	return code
}
